package com.funmi.lizip.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.funmi.lizip.common.base.R;
import com.funmi.lizip.entity.*;
import com.funmi.lizip.entity.dto.patrol.PatrolAddRequest;
import com.funmi.lizip.entity.dto.patrol.PatrolQueryRequest;
import com.funmi.lizip.entity.dto.patrol.PatrolUpdateRequest;
import com.funmi.lizip.entity.dto.personnel.PersonnelQueryRequest;
import com.funmi.lizip.entity.vo.PatrolQueryVo;
import com.funmi.lizip.entity.vo.PatrolVo;
import com.funmi.lizip.entity.vo.PersonnelVo;
import com.funmi.lizip.service.PatrolService;
import com.funmi.lizip.service.PatrolTrackService;
import com.funmi.lizip.service.PersonnelService;
import com.funmi.lizip.service.UserService;
import com.funmi.lizip.utils.ListToPageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yeyg
 * @since 2022-11-03
 */
@Api(tags = "巡护任务模块")
@RestController
@RequestMapping("/patrol")
public class PatrolController {
    @Autowired
    private PatrolService patrolService;
    @Autowired
    @Lazy
    private PersonnelService personnelService;
    @Autowired
    @Lazy
    private PatrolTrackService patrolTrackService;

    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "查询巡护任务详情")
    @GetMapping("/{id}")
    public R get(@PathVariable int id){
        if (id <= 0){
            return R.success().data("非法id");
        }
        // Page<PatrolQueryVo> patrol = patrolService.getPatrol(id);
        Patrol patrol = patrolService.getById(id);
        return R.success().data(patrol);
    }

    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "修改巡护任务")
    @PutMapping("")
    public R update(@RequestBody HashMap<String, Object> request){
        Patrol patrol = JSONObject.parseObject(JSONObject.toJSONBytes(request), Patrol.class);
        /*if (request.get("rangerIds") != null && request.get("rangerIds") != "") {
            patrol.setRangerIds(new JSONObject((Map<String, Object>) request.get("rangerIds")));
        }*/
        Object name = request.get("name");
        Personnel one = personnelService.getOne(new QueryWrapper<>(new Personnel(name.toString())));
        if (one==null){
            return R.success().data("修改失败");
        }
        String json = "{\"id\": \""+one.getId()+"\", \"name\": \""+name.toString()+"\"}";
        JSONObject jsonObject = JSONObject.parseObject(json);
        patrol.setRangerIds(jsonObject);
        if (patrol.getId() <= 0){
            return R.success().data("修改失败");
        }
        boolean update = patrolService.updateById(patrol);
        if (update){
            return R.success().data("修改成功");
        }
        return R.success().data("修改失败");
    }

    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "新增")
    @PostMapping("")
    public R add(@RequestBody HashMap<String, Object> request){
        if (ObjectUtils.isEmpty(request)){
            return R.success().message("数据为空");
        }
        Patrol patrol = JSONObject.parseObject(JSONObject.toJSONBytes(request), Patrol.class);
        Object name = request.get("name");
        if (ObjectUtils.isEmpty(name)){
            return R.success().message("请指定已注册的巡护人员");
        }
        Personnel one = personnelService.getOne(new QueryWrapper<>(new Personnel(name.toString())));
        if (one==null){
            return R.fail().data("新增失败");
        }
        String json = "{\"id\":\""+one.getId()+"\", \"name\":\""+name.toString()+"\"}";
        JSONObject jsonObject = JSONObject.parseObject(json);
        patrol.setRangerIds(jsonObject);
        patrol.setDelete(false);
        patrol.setCreateAt(LocalDateTime.now());

        boolean save = patrolService.save(patrol);
        if (save){
            return R.success().data("新增成功");
        }
        return R.fail().data("新增失败");
    }

    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "删除")
    @DeleteMapping("/{id}")
    public R update(@PathVariable int id){
        boolean b = patrolService.removeById(id);
        if (b){
            return R.success().data("删除成功");
        }
        return R.success().data("删除失败");
    }


    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "新增巡护任务参数示例")
    @PostMapping("/testAdd")
    public R addTest(@RequestBody(required = false) PatrolAddRequest request){
        return R.success().data("啦啦啦啦啦");
    }
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "修改巡护任务参数示例")
    @PutMapping("/testUpdate")
    public R updateTest(@RequestBody(required = false) PatrolUpdateRequest request){
        return R.success().data("啦啦啦啦啦");
    }


    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "分页获取巡护任务信息")
    @GetMapping("")
    public R getList(PatrolQueryRequest request) {
        long current = 1;
        long size = 10;
        Patrol patrolQuery = new Patrol();
        if (request != null) {
            BeanUtils.copyProperties(request, patrolQuery);
            current = request.getPage();
            size = request.getPageSize();
        }
        
        QueryWrapper<Patrol> queryWrapper = new QueryWrapper<>(patrolQuery);
        queryWrapper.orderByDesc("create_at");
        if (!ObjectUtils.isEmpty(request) && !ObjectUtils.isEmpty(request.getId())) {
            Integer id = request.getId();
            /*Personnel personnel = personnelService.getById(id);
            String ranger_ids = "{\"id\":\b\""+id+"\",\b\"name\":\b\""+personnel.getName()+"\"}";
            JSONObject jsonObject = JSONObject.parseObject(ranger_ids, Feature.OrderedField);
            queryWrapper.eq("ranger_ids", jsonObject);*/
            QueryWrapper<Patrol> patrolQueryWrapper = new QueryWrapper<>();
            if (!ObjectUtils.isEmpty(request) && !ObjectUtils.isEmpty(request.getStatus())) {
                patrolQueryWrapper.eq("status", request.getStatus());
            }
            List<Patrol> list = patrolService.list(patrolQueryWrapper);
            List<Patrol> collect = list.stream().filter(patrol -> id == Integer.parseInt(patrol.getRangerIds().getString("id"))).collect(Collectors.toList());
            List<Patrol> limitList = ListToPageUtil.getLimitList(collect, (int) current, (int) size);
            return R.success().data(limitList);
        }


        Page<Patrol> patrolPage = patrolService.page(new Page<>(current, size), queryWrapper);
        PageDTO<PatrolVo> patrolVoPage = new PageDTO<>(patrolPage.getCurrent(), patrolPage.getSize(), patrolPage.getTotal());
        List<PatrolVo> patrolVoList = patrolPage.getRecords().stream().map(patrol -> {
            PatrolVo patrolVo = new PatrolVo();
            BeanUtils.copyProperties(patrol, patrolVo);
            /*QueryWrapper<Personnel> personnelQueryWrapper = new QueryWrapper<>();
            personnelQueryWrapper.eq("ranger_duty_area_code", patrol.getDutyAreaCode());
            List<Personnel> list = personnelService.list(personnelQueryWrapper);
            if (!ObjectUtils.isEmpty(list) && list.size() > 0){
                patrolVo.setRangerPatrolRegion(list.get(0).getRangerPatrolRegion());
            }else {
                patrolVo.setRangerPatrolRegion("");
            }*/
            return patrolVo;
        }).collect(Collectors.toList());
        patrolVoPage.setRecords(patrolVoList);
        return R.success().data(patrolVoPage);
    }




    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "通过巡护任务id开始巡护")
    @PutMapping("/start/{id}")
    public R start(@PathVariable int id){
        Patrol patrol = new Patrol();
        if (id <= 0){
            return R.fail().data("开始失败");
        }
        Patrol byId = patrolService.getById(id);
        // 未做是否是未开始的任务 即 未判断status是否为0.
        patrol.setId(id);
        patrol.setStartTime(LocalDateTime.now());
        patrol.setStatus(1);
        boolean update = patrolService.updateById(patrol);
        // 添加一条轨迹
        // 从登录态中获取
        /*SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        String name = authentication.getName();
        QueryWrapper<Personnel> personnelQueryWrapper = new QueryWrapper<>();
        personnelQueryWrapper.eq("contact_tel", name);
        Personnel one = personnelService.getOne(personnelQueryWrapper);*/
        JSONObject rangerIds = byId.getRangerIds();
        Object id1 = rangerIds.get("id");


        QueryWrapper<PatrolTrack> patrolTrackQueryWrapper = new QueryWrapper<>();
        patrolTrackQueryWrapper.eq("ranger_id", id1);
        patrolTrackQueryWrapper.eq("status", true);
        if (!ObjectUtils.isEmpty(patrolTrackService.getOne(patrolTrackQueryWrapper))){
            return R.fail().message("您有正在进行的轨迹");
        }

        PatrolTrack patrolTrack = new PatrolTrack();
        patrolTrack.setRangerId(id1.toString());
        patrolTrack.setStatus(true);
        patrolTrack.setPatrolId(String.valueOf(id));
        // 设备编号 未设置
        boolean save = patrolTrackService.save(patrolTrack);
        if (!save){
            return R.fail().message("轨迹添加失败");
        }
        if (update){
            return R.success().message("开始成功");
        }
        return R.success().message("开始失败");
    }


}

